package passenger

import (
	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/passenger"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/rider"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/policies"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"github.com/gofiber/fiber/v2"
	"github.com/spf13/cast"
)

type RidersController struct {
	v1.BaseController
}

func (controller *RidersController) Index(c *fiber.Ctx) error {
	riders := rider.GetRidersByUserId(controller.Auth(c))
	return controller.Json(c, riders)
}

func (controller *RidersController) Show(c *fiber.Ctx) error {
	riderModel := rider.Get(cast.ToUint64(c.Params("id")))
	if riderModel.ID == 0 {
		return controller.NotFound(c)
	}
	userId := controller.Auth(c)

	if ok := policies.CanViewRider(userId, riderModel); !ok {
		return controller.Forbidden(c)
	}

	return controller.Json(c, riderModel)
}

func (controller *RidersController) Store(c *fiber.Ctx) error {

	request := new(requests.RiderRequest)

	if errors := requests.ValidateRider(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	passenger := c.Locals("passenger").(passenger.Passenger)

	UserId := controller.Auth(c)

	riderModel := rider.Rider{
		UserId:      UserId,
		PassengerId: passenger.ID,
		Name:        request.Name,
		Phone:       request.Phone,
		Gender:      request.Gender,
	}

	riderModel.Create()
	if riderModel.ID > 0 {
		return controller.Success(c)
	} else {
		return controller.Faield(c, "创建失败")
	}
}

func (controller *RidersController) Update(c *fiber.Ctx) error {

	riderModel := rider.Get(cast.ToUint64(c.Params("id")))
	if riderModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)
	if ok := policies.CanModifyRider(userId, riderModel); !ok {
		return controller.Forbidden(c)
	}

	request := new(requests.RiderRequest)

	if errors := requests.ValidateRider(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	riderModel.Name = request.Name
	riderModel.Phone = request.Phone
	riderModel.Gender = request.Gender

	rowsAffected := riderModel.Save()
	if rowsAffected > 0 {
		return controller.Success(c)
	} else {
		return controller.Faield(c, "更新失败")
	}
}

func (controller *RidersController) Delete(c *fiber.Ctx) error {

	riderModel := rider.Get(cast.ToUint64(c.Params("id")))
	if riderModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)

	if ok := policies.CanDeleteRider(userId, riderModel); !ok {
		return controller.Forbidden(c)
	}

	rowsAffected := riderModel.Delete()

	if rowsAffected > 0 {
		return controller.Success(c)
	}

	return controller.Faield(c, "删除失败")
}
